<?php
/*
  This page's claim to fame is a stormwater selector panel.  Recommendation calcs are done based on that.
  applyGoal() is the key function that comes from the calc .js.
*/
?>

<?php
  if (!isset($_COOKIE['ys-parcelNum'])) {
    setcookie('noParcelNum',true);
    $u = explode('/',$_SERVER['REQUEST_URI']);
    array_pop($u);
    $u = 'http://'.$_SERVER['SERVER_NAME'].implode('/',$u).'/?page=introLocation';
    header('Location: '.$u);
  }
  $isRegistered = isset($_SESSION['gdusername']) AND isset($_SESSION['gdpassword']);

  $alertNoStormwater = false;
  if (isset($_COOKIE['noStormwater'])) {
    $alertNoStormwater = true;
    setcookie('noStormwater','',time() - 3600);
  }

  $thumbnail = 'img/blank.png';
  if (isset($_COOKIE['ys-parcelThumbnail'])) {
    $thumbnail = substr($_COOKIE['ys-parcelThumbnail'],2);
  }

  include_once('util.php');
  $glossary = buildGlossary('Stormwater');
?>
  <body onload="Ext.onReady(function(){init()})">
    <script>
      var thumbDetailsWindow;
      var thumbDetailsWindowLastPos;
      var stormwaterGridPanel;
      var goalsStore;
      var performanceStore;
      var stormwaterControlConstraintStore;
      var pollutionReductionPercent = <?php echo substr($_COOKIE['ys-parcelRegulated'],2) == 'True' ? 65 : 10?>;

      function init() {
        document.getElementById('stormwaterGridPanel').style.visibility = 'visible';

        Ext.get('loading').fadeOut({duration : 0.2,remove : true});
        Ext.QuickTips.init();

        var cp = new Ext.state.CookieProvider({
          expires : new Date(new Date().getTime()+(1000*60*60*24*30)) //30 days
        });
        Ext.state.Manager.setProvider(cp);

        goalsStore                       = initGoalsStore();
        goalsStore.each(function(rec) {
          if (rec.get('showOnIntroPage') != 'yes') {
            goalsStore.remove(rec);
          }
        });
        performanceStore                 = initPerformanceStore();
        stormwaterControlConstraintStore = initBmpConstraintStore();

        if (cp.get('pollutionReductionPercent')) {
          pollutionReductionPercent = cp.get('pollutionReductionPercent');
        }

        // create a fake parcelInfoStore based on cookies
        var parcelInfoStore = new Ext.data.ArrayStore({
          fields : [
             'Regulated'
            ,'Owner Name'
            ,'Dep2HWT (in)'
            ,'Dep2ResLyr (in)'
            ,'Hyd Soil Group'
            ,'KSat (in/hr)'
            ,'Imperv Area (ac)'
            ,'UpLand Area (ac)'
            ,'Wetland Area (ac)'
            ,'Total Area (ac)'
            ,'Perv Load (lb/yr)'
            ,'Imperv Load'
            ,'Total Load (lb/yr)'
            ,'Slope (%)'
            ,'Load Credit/Deficit (lb/yr)'
          ]
          ,data : [[
             cp.get('parcelRegulated')
            ,cp.get('parcelOwner Name')
            ,cp.get('parcelDep2HWT (in)')
            ,cp.get('parcelDep2ResLyr (in)')
            ,cp.get('parcelHyd Soil Group')
            ,cp.get('parcelKSat (in/hr)')
            ,cp.get('parcelImperv Area (ac)')
            ,cp.get('parcelUpLand Area (ac)')
            ,cp.get('parcelWetland Area (ac)')
            ,cp.get('parcelTotal Area (ac)')
            ,cp.get('parcelPerv Load (lb/yr)')
            ,cp.get('parcelImperv Load')
            ,cp.get('parcelTotal Load (lb/yr)')
            ,cp.get('parcelSlope (%)')
            ,cp.get('parcelLoad Credit/Deficit (lb/yr)')
          ]]
        });

        // Here is where the magic happens when a user selects a row.
        var sm = new Ext.grid.CheckboxSelectionModel({
           singleSelect : true
          ,checkOnly    : true
          ,listeners    : {
            rowdeselect : function(sm,idx,rec) {
            }
            ,rowselect : function(sm,idx,rec) {
              // yum, cookies
              cp.set('stormwaterShort',rec.get('short'));
              cp.set('stormwaterFull',rec.get('full'));
              cp.set('stormwaterDetails',rec.get('details'));
              cp.clear('totalCost');
              document.getElementById('stormwaterControl').innerHTML = rec.get('full');
              // calcs, calcs, calcs
              var wqd         = calcWQD(rec.get('short'),pollutionReductionPercent / 100,performanceStore);
              var loadRemoved = calcLoadRemoved(rec.get('short'),wqd,parcelInfoStore,performanceStore);
              var costFactor  = getBmpConstraintCostFactor('Partly developed area',stormwaterControlConstraintStore);
              var unitCost    = getBmpTypeUnitCost(rec.get('full'),stormwaterGridPanel.getStore());
              var wqVolume    = calcWQVolume(parcelInfoStore,wqd);
              var totalCost   = costFactor * unitCost * wqVolume;
              unitCost        = totalCost / loadRemoved;
              cp.set('totalCost',totalCost);
              document.getElementById('designCost').innerHTML = '$' + CommaFormatted(new String(Math.round(totalCost)));
              var recommendation = [];
              if (new RegExp(/^(C|D|C\/D|U)$/).test(parcelInfoStore.getAt(0).get('Hyd Soil Group'))) {
                if (parcelInfoStore.getAt(0).get('Regulated') == 'True') {
                  recommendation.push('<font color="red">Soils on this parcel may be very low quality for filtering stormwater. Consider buying credits in order to meet permit requirements.</font>');
                }
                else {
                  recommendation.push('<font color="red">Soils on this parcel may be very low quality for filtering stormwater. Pollution reduction may not be possible for this unregulated site.</font>');
                }
              }
              else if (new RegExp(/^(A|B|A\/B|B\/C)$/).test(parcelInfoStore.getAt(0).get('Hyd Soil Group'))) {
                if (unitCost <= 22000) {
                  recommendation.push('<font color="green">You have chosen an economic option.</font>');
                }
                else {
                  recommendation.push('<font color="#cd853f">Your choice has a relatively high unit cost. You may want to consider other Controls.</font>');
                }
              }
              document.getElementById('notice').innerHTML = recommendation.join('<br>');
            }
          }
        });

        // assign weights so that we can order the options
        var initGoal = cp.get('goal') ? cp.get('goal') : 'Cost';
        goalsStore.each(function(r) {
          r.set('weight',r.get('name') == initGoal ? 3 : 1);
          r.commit();
        });

        // the actual gridpanel
        stormwaterGridPanel = new Ext.grid.GridPanel({
           store            : initBmpTypeStore()
          ,columns          : [
             sm
            ,{id : 'short',dataIndex : 'short',width : 90,align : 'center',renderer : function(val,p,rec) {
              return '<img id="info.' + val + '" src="images/' + val + '.png" title="' + rec.get('full') + '">';
            }}
            ,{id : 'details',dataIndex : 'detailsAbbrev',renderer : function(val,p,rec) {
              return '<span class="bold">' + rec.get('full') + '.</span> ' + val;
            }}
          ]
          ,sm               : sm
          ,autoExpandColumn : 'details'
          ,remoteSort       : true
          ,renderTo         : 'stormwaterGridPanel'
          ,id               : 'stormwaterGridPanelCmp'
          ,height           : 344
          ,hideHeaders      : true
          ,tbar             : ['->','Sort by: ',' ',new Ext.form.ComboBox({
             width          : 200 
            ,store          : goalsStore
            ,forceSelection : true
            ,triggerAction  : 'all'
            ,selectOnFocus  : true
            ,mode           : 'local'
            ,editable       : false
            ,displayField   : 'name'
            ,valueField     : 'name'
            ,listeners      : {
              afterrender : function(combo) {
                combo.setValue(initGoal);
              }
              ,select : function(combo,rec) {
                var g = rec.get('name');
                cp.set('goal',g);
                combo.getStore().each(function(r) {
                  r.set('weight',r.get('name') == g ? 3 : 1);
                  r.commit();
                });
                applyGoal(combo.getStore(),parcelInfoStore,stormwaterGridPanel.getStore(),Ext.getCmp('stormwaterGridPanelCmp'));
              }
            }
          })]
          ,listeners        : {
            viewready : function(grid) {
              applyGoal(goalsStore,parcelInfoStore,stormwaterGridPanel.getStore());
              var idx = cp.get('stormwaterShort') ? stormwaterGridPanel.getStore().findExact('short',cp.get('stormwaterShort')) : 0;
              grid.getSelectionModel().selectRow(idx);
              grid.getView().focusRow(idx);
            }
            ,cellclick : function(grid,rowIndex,columnIndex,e) {
              if (columnIndex == 0 || columnIndex == 2) {
                grid.getSelectionModel().selectRow(rowIndex);
              }
              else {
                showThumbDetailsWindow(grid.getStore().getAt(rowIndex).get('short'),250,400,475);
              }
            }
          }
        });

<?php
  if ($alertNoStormwater) {
?>
        Ext.Msg.alert('No storm water control selected',"You were brought back to this page because you need to select a storm water control before continuing.");
<?php
  }
?>
      }

      // Show a popup window w/ a larger image and more stormwater details.
      function showThumbDetailsWindow(id,x,y,w) {
        var rec = stormwaterGridPanel.getStore().getAt(stormwaterGridPanel.getStore().findExact('short',id));
        if (!Ext.getCmp('thumbDetailsWindow')) {
          thumbDetailsWindow = new Ext.Window({
             id          : 'thumbDetailsWindow'
            ,plain       : true
            ,defaults    : {border : false}
            ,autoHeight  : true
            ,listeners   : {
              move : function(p) {
                thumbDetailsWindowLastPos = p.getPosition();
              }
              ,beforeclose : function(p) {
                thumbDetailsWindowLastPos = p.getPosition();
              }
            }
          });
        }
        thumbDetailsWindow.setWidth(w);
        thumbDetailsWindow.removeAll();
        thumbDetailsWindow.setTitle(rec.get('full'));
        var html = [
          '<table><tr><td><img width=220 height=220 src="images/' + rec.get('short') + '1.png"></td><td><img width=220 height=220 src="images/' + rec.get('short') + '2.png"></td></tr><tr><td colspan=2>'
          ,rec.get('details')
          ,'</td></tr></table>'
        ].join('');
        thumbDetailsWindow.add({html : html});
        if (!thumbDetailsWindowLastPos) {
          thumbDetailsWindow.setPosition(x,y);
        }
        else {
          thumbDetailsWindow.setPosition(thumbDetailsWindowLastPos);
        }
        thumbDetailsWindow.show();
        thumbDetailsWindow.doLayout();
        thumbDetailsWindow.syncShadow();
      }
    </script>

    <style>
      .x-grid3-cell-inner, .x-grid3-hd-inner {
        overflow:hidden;
        padding:3px 3px 3px 5px;
        white-space:normal;
      }
      .x-grid3-row-checker, .x-grid3-hd-checker {
        background-image:url(images/row-radio-sprite.gif);
      }
      .x-grid3-row td, .x-grid3-summary-row td {
        vertical-align : middle;
      }
      .bold {
        font-weight : 900;
      }
      #stormwaterDiv {
        width    : 500px;
        height   : 344px;
        position : relative;
      }
      #stormwaterGridPanel {
        top        : 0px;
        left       : 0px;
        width      : 500px;
        height     : 344px;
        visibility : hidden;
      }
    </style>

    <div id="site">
<?php include_once('header.php')?>
        <div id="content">

            <div class="home-screen clearfix">

                <div class="left-column" style="width: 500px;">
                    <h2 style="margin-bottom: 20px;">Select a stormwater control.</h2>
                                <p>Listed below are ten recommended <?php echo $glossary['stormwater control']['a']?> control design solutions.  An estimate of the design cost for the selected parcel will be adjusted as you change your selection.  Default sort will be cost.</p><?php echo $glossary['stormwater control']['div']?>
                                <div id="stormwaterDiv">
                                  <div id="loading"><span id="loading-message">Loading. Please wait...</span></div>
                                  <div id="stormwaterGridPanel"></div>
                                </div>
                        </div>
                        <div class="right-column">
                          <table id="blue-box">
                            <tr><th><div id="step-three" class="progress-bar">&nbsp;</div></th></tr>
                            <tr><td>
                              <div id="small_map"><img src="<?php echo $thumbnail?>"></div>
<?php
  if ($isRegistered) {
?>
                              <p><label class="item first">Property Owner:</label><label><?php echo substr($_COOKIE['ys-parcelOwner_Name'],2)?></label></p>
<?php
}
else {
?>
                              <p><label class="item first">Property Address:</label><label><?php echo substr($_COOKIE['ys-parcelPhys_Addr1'],2).', '.substr($_COOKIE['ys-parcelPhys_City'],2)?></label></p>
<?php
}
?>
                              <p>
                                <label class="item">Area (Acres)</label><br>
                                <label class="item">Total:</label><label><?php echo sprintf("%.2f",substr($_COOKIE['ys-parcelTotal_Area_(ac)'],2))?></label><br>
                                <label class="item">Impervious:</label><label><?php echo sprintf("%.2f",substr($_COOKIE['ys-parcelImperv_Area_(ac)'],2))?></label>
                              </p>
                              <p><label class="item">Stormwater Control:</label><label id="stormwaterControl"></label></p>
                              <p><label class="item">Design Cost:</label><label id="designCost"></label></p>
                              <p class="notice" id="notice"></p>
                            </td></tr>
                          </table>
                    <p style="text-align: center; margin-top: 10px; margin-left: 30px; width: 240px;"><a class="info" id="design cost calculated" href="#">How is the design cost calculated?</a></p>
                        </div>
                        <div style="padding-top: 20px; clear: both;">
                        				<p>Exchange will give design recommendations for a new structure. If you want to consider modifying an existing control, you will need to follow the <a href="?page=proSolution">Advanced Track</a>.</p>
                                <p>Click Next to continue to the next step.</p>
                                <a href="?page=introRegulated"><img src="images/back_but.png" style="vertical-align: top; margin-top: 10px;" alt="Back" title="Back" /></a>
                                                                                <a href="?page=introPollution"><img src="images/next_but.png" style="vertical-align: top; margin-left: 570px; margin-top: 10px;" alt="Next" title="Next" /></a>                                               </div>

            </div>

        </div>
<?php include_once('footer.php')?>
    </div>
<script type="text/javascript">
<?php
  foreach ($glossary as $k => $v) {
    $tNoSpace = str_replace(' ','',$k);
    echo '$(\'a#glossary_t_'.$tNoSpace.'\').click(function(e){e.preventDefault();}).hover(function(e){$(\'#glossary_d_'.$tNoSpace.'\').show();}, function(e){$(\'#glossary_d_'.$tNoSpace.'\').hide();});'."\n";
  }
?>
</script>
    <script type="text/javascript" src="./js/ext-3.4.0/adapter/ext/ext-base.js"></script>
    <script type="text/javascript" src="./js/ext-3.4.0/ext-all.js"></script>
    <script type="text/javascript" src="./js/calcs.js"></script>
    <script type="text/javascript">
      $(document).ready(function(){
        var clickHereLinks = initClickHereLinks('introStormwater');
        infoWindow = $('table#info-window');
        $('a.info').click(function(e){
          e.preventDefault();
          $('table#info-window tr:eq(1) td:first').html(clickHereLinks[$(this).attr('id')]);
          infoWindow.show()
        });
        $('table#info-window tr td a').click(function(e){
          e.preventDefault();
          infoWindow.hide();
        });
        $('body').live('keydown', function (e) {
            if (infoWindow.css('display') != 'none'){
                var charCode = e.charCode || e.keyCode;
                if (charCode == 27)
                    infoWindow.css('display', 'none');
            }
        });
      });
    </script>
    <table id="info-window">
      <tr><td style="margin:0;padding:4px 7px 0 0;text-align:right;font-size: 16px;font-weight:bold;"><a href="" style="text-decoration:none;">X</a></td></tr>
      <tr><td style="padding-top:0;"></td></tr>
      <tr><td style="text-align: center; padding: 0;"><a href="">close</a></td></tr>
    </table>
  </body>
